package cn.lunkr.webview_sync_cookies;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.util.HashMap;
import java.util.Map;

import cn.lunkr.webview_sync_cookies.util.SystemUtil;
import cn.lunkr.webview_sync_cookies.view.SurpriseLayout;

public class MainActivity extends AppCompatActivity implements SurpriseLayout.ChangeTitle {


    /*****************************************************
     * 替换主app sid，cookies
     *
     * Coremail=af351e34ab40f70094222b63deeb74c9;Coremail.sid=BARPDWaaiBcdRzPFTKaaQJDBObimdLWN
     */
    String sid = "CAOotCZZKVodkcVGiqZZLNbfkXPdozzq";
    String cookies = "33fc7fbfef8e1c16f2ff55d5c1e0084f";
    String mUrl = "https://mt.icoremail.net/coremail/hxphone/sso.html#/frame/folder/1?coremail_userid=bwen%40coremail.cn&coremail_username=%E6%96%87%E6%96%8C&domain=coremail.cn&sid=" + sid;

    /**
     *     String sid = "BARPDWaaiBcdRzPFTKaaQJDBObimdLWN";
     *     String cookies = "af351e34ab40f70094222b63deeb74c9";
     *     String mUrl = "http://lunkrcm05.rd.mt/coremail/hxphone/#/frame/folder/1";
     */

    private SurpriseLayout mSurpriseLayout;

    private WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSurpriseLayout = findViewById(R.id.surprise_layout);
        mSurpriseLayout.setChangeTitle(this);
        initData();
    }


    @Override
    public void onChangeTitle(String title) {

    }

    public void synCookies() {
        HashMap<String, String> cookieMap = new HashMap<>();
        String domain = SystemUtil.getUrlDomain(mUrl);
        cookieMap.put(domain, new StringBuilder("Coremail=").append(cookies).append(";Coremail.sid=").append(sid).toString());
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        if (cookieMap != null && cookieMap.size() > 0) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                cookieManager.removeSessionCookies(null);//移除
                cookieManager.setAcceptThirdPartyCookies(mWebView, true);//5.0以上不再默认可以，所以要主动设置
            } else {
                cookieManager.removeSessionCookie();//移除
            }
            cookieManager.setAcceptCookie(true);
            for (Map.Entry<String, String> entity : cookieMap.entrySet()) {
                String value = entity.getValue();
                if (!TextUtils.isEmpty(value)) {
                    String[] arr = value.split(";");
                    if (arr != null && arr.length > 0) {
                        for (String s : arr) {
                            // 根据具体hxhpone 的部署路径，是否需要加 path 参数配置。
//                            cookieManager.setCookie(entity.getKey(), s  + ";path=/");
                            cookieManager.setCookie(entity.getKey(), s);
                        }
                    }
                }
            }
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.flush();
        } else {
            CookieSyncManager.createInstance(this);
            CookieSyncManager.getInstance().sync();
        }
    }


    @SuppressLint("JavascriptInterface")
    private void initData() {
        mWebView = mSurpriseLayout.getWebView();
        synCookies();
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setDisplayZoomControls(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
//        Chrome调试WebView， 步骤：1  mWeb.setWebContentsDebuggingEnabled(true);  2  在Chrome地址栏输入：Chrome://inspect   点 inspect， 访问 devtools：  tips:需要翻墙。
//        mWebView.setWebContentsDebuggingEnabled(true);  调试模式
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }


        // 下列代码是为了实现下载文件使用
        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
//                LogUtil.d(TAG, "mUrl:"+ mUrl);

            }
        });
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                // 忽略证书校验
                // http://blog.csdn.net/sd19871122/article/details/54632199
                handler.proceed();
            }

            //Android N(7.0)之前执行这里
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }

            //Android N之后执行这里
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }
        });
        mWebView.addJavascriptInterface(this, "lunkrApp");
        if (TextUtils.isEmpty(mUrl)) {
            return;
        }
        if (SystemUtil.isLink(mUrl)) {
            mWebView.loadUrl(mUrl);
        } else {
            setTitle("");
            mWebView.loadDataWithBaseURL("about:blank", mUrl, "text/html", "utf-8", null);
        }
        mSurpriseLayout.setListener(new SurpriseLayout.SurpriseListener() {
            @Override
            public void closeWindow() {
                MainActivity.this.finish();
            }
        });
    }

    /**
     * 注入js 方法，执行关闭Activity， 规避 window.close 存在兼容问题
     * 调用方式 javascript:lunkrApp.closeWindow()
     */
    @JavascriptInterface
    public void closeWindow() {
    }
}
